package com.pokermadness.servlets;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class GenericServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3489252560559790991L;

	public void init() {
		ServletContext context = getServletContext();
		if (context.getAttribute("active-sessions") == null)
			context.setAttribute("active-sessions",
					new HashMap<String, HttpSession>());
	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
		@SuppressWarnings("unchecked")
		HashMap<String, HttpSession> map = (HashMap<String, HttpSession>) getServletContext()
				.getAttribute("active-sessions");
		String key = getCookieValue(request.getCookies(), "session", "-1");
		
		if (map.containsKey(key)) {
			session = map.get(key);
		} else {
			session = request.getSession(true);
			session.setMaxInactiveInterval(3600);
		}
		
		request.setAttribute("session", session);
		
		Cookie cookie = new Cookie("session", session.getId());
		cookie.setMaxAge(3600);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		response.setContentType("application/json");
	}
	
	private String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		if (cookies == null)
			return defaultValue;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

}
